﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using _PLATFORM.DATA;

namespace _PLATFORM.WEB.Controllers
{ 
    public class TemplateController : Controller
    {
        private eCommPlatformRepoEntities db = new eCommPlatformRepoEntities();

        //
        // GET: /Template/

        public ViewResult Index()
        {
            var templates = db.TEMPLATEs;
            return View(templates.ToList());
        }

        //
        // GET: /Template/Details/5

        public ViewResult Details(Guid id)
        {
            TEMPLATE template = db.TEMPLATEs.Find(id);
            return View(template);
        }

        //
        // GET: /Template/Create

        public ActionResult Create()
        {
            //ViewBag.USER_ID = new SelectList(db.FRAMEWORK_USER, "USER_ID", "FIRST_NAME");
            return View();
        } 

        //
        // POST: /Template/Create

        [HttpPost]
        public ActionResult Create(TEMPLATE template, IEnumerable<HttpPostedFileBase> fileBase, string AccentColor, string NavColor, string Chk_UseResellerInventory)
        {
            if (ModelState.IsValid)
            {
                template.USER_ID = DATA.Custom_Classes.User.UserID;

                // Make Entry In RESELLER_TEMPLATE TABLE
                // Find Reseller ID
                var reseller = db.RESELLERs.Where(r => r.USER_ID == template.USER_ID).ToList();
                
                // Get The Logo
                HttpPostedFileBase mFile = Request.Files[0];
                template.LOGO = template.USER_ID.ToString() + "_" + mFile.FileName;
                var imagePath = Server.MapPath("~\\Assets\\UserTemplateLogos\\" + template.LOGO);
                mFile.SaveAs(imagePath);

                template.RESELLER = reseller[0];
                template.RESELLER_ID = reseller[0].RESELLER_ID;

                template.NAVI_COLOR_SCHEME = NavColor;
                template.SITE_COLOR_SCHEME = AccentColor;

                // Put User In "Reseller" Role
                Roles.AddUserToRole(User.Identity.Name, "Reseller");
                
                // Assume Reseller Wants To Use Default Inventory
                var frameWorkUser = db.FRAMEWORK_USER.Find(template.USER_ID);
                frameWorkUser.USE_DEFAULT_INVENTORY = (Chk_UseResellerInventory == "on") ? 1 : 0;

                // Find The Default Account's User ID To Set As Parent ID
                var parent = Membership.GetUser(ConfigurationSettings.AppSettings["ProductOwnerUserName"]);
                DATA.Custom_Classes.User.ParentID = Guid.Parse(parent.ProviderUserKey.ToString());

                frameWorkUser.PARENT_ID = DATA.Custom_Classes.User.ParentID;

                db.Entry(frameWorkUser).State = EntityState.Modified;
                db.SaveChanges();

                try
                {
                    template.FRAMEWORK_USER = frameWorkUser;
                    db.TEMPLATEs.Add(template);
                    db.SaveChanges();
                }catch (DbEntityValidationException dbEx){

                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        }
                    }

                }

                return RedirectToAction("ResellerHome", "Account");  
            }

            ViewBag.USER_ID = new SelectList(db.FRAMEWORK_USER, "USER_ID", "FIRST_NAME", template.USER_ID);
            return View(template);
        }
        
        //
        // GET: /Template/Edit/5
 
        public ActionResult Edit(Guid id)
        {
            TEMPLATE template = db.TEMPLATEs.Find(id);
            ViewBag.USER_ID = new SelectList(db.FRAMEWORK_USER, "USER_ID", "FIRST_NAME", template.USER_ID);
            return View(template);
        }

        //
        // POST: /Template/Edit/5

        [HttpPost]
        public ActionResult Edit(TEMPLATE template)
        {
            if (ModelState.IsValid)
            {
                db.Entry(template).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.USER_ID = new SelectList(db.FRAMEWORK_USER, "USER_ID", "FIRST_NAME", template.USER_ID);
            return View(template);
        }

        //
        // GET: /Template/Delete/5
 
        public ActionResult Delete(Guid id)
        {
            TEMPLATE template = db.TEMPLATEs.Find(id);
            return View(template);
        }

        //
        // POST: /Template/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(Guid id)
        {            
            TEMPLATE template = db.TEMPLATEs.Find(id);
            db.TEMPLATEs.Remove(template);
            db.SaveChanges();
            return RedirectToAction("Index");
        }


        //
        // GET: /Template/Load/5

        public ActionResult Load(decimal ResellerID)
        {
            TEMPLATE Template = db.TEMPLATEs.Where(t => t.RESELLER_ID == ResellerID).ToList()[0];
            ViewBag.Template = Template;

            return RedirectToAction("ResellerIndex", "Home", Template);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}